<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\ResponseException;
use App\Handler\sendMsgHandler;
use App\Http\Requests\Api\LoginRequest;
use App\Http\Requests\Api\RegisterRequest;
use App\Http\Requests\Api\UserRegRequest;
use App\Jobs\RegSuccNotify;
use App\Models\User;
use App\Models\WechatUser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Facades\JWTAuth;

class LoginController extends Controller
{
    use sendMsgHandler;

    /**
     * 发送注册验证短信
     * User: Clannad ~ ☆
     * * @throws ResponseException
     */
    public function sendRegEmailVerifyCode(Request $request)
    {
        //未发送的时候
        $email = $request->input('email');

        $validator = \Validator::make($request->all(), [
            'email' => 'required|email|unique:user,email|max:50',
        ]);

        //验证邮箱的唯一性等
        if ($validator->fails()) {
            $errors = $validator->errors();
            throw new ResponseException(400,$errors->first('email'));
        }

        $res = $this->sendEmailMsg($email);

        throw new ResponseException(200, '发送成功', $res);
    }

	/**
	 * 用户注册
	 * User: Clannad ~ ☆
	 * DateTime: 2019/11/1 11:29
	 * @param RegisterRequest $request
	 * @throws ResponseException
	 */
	public function register(RegisterRequest $request)
    {

		$data = $request->all();

        $email = $data['email'];
        $code = $data['code'];
        $verify_str = $data['verify_str'];
        $verify_code = Redis::get($verify_str);

        if ( ! $verify_code) {
            throw new ResponseException(400, '注册验证码已过期，请重新发送');
        }

        if ($verify_code != $code) {
            throw new ResponseException(400, '验证码不正确');
        } else {
            $hashKey = 'send_email:' . $email;
            Redis::del($verify_str);//确认完就清除掉
            Redis::del($hashKey);//确认完就清除掉
        }

		$user = User::create([
			'username'=>$data['username'],
			'password'=>bcrypt($data['password']),
			'pay_password'=>bcrypt(123456),
			'tel'=>$data['tel'],
			'nick_name'=>$data['nick_name'],
			'email'=>$data['email'],
		]);

		if($user->id){
			//写入附表
			$user->user_info()->create([
				'age'=> 1,
				'sex'=>$data['sex'] ?? 0,
			]);

			//队列通知
			dispatch(new RegSuccNotify($user['email'],$user['username']));

			$token = JWTAuth::fromUser($user); //注册成功后直接登录
			throw new ResponseException(200,'注册成功',$token);
		}else{
			throw new ResponseException(500,'注册失败，请稍后再试');
		}
    }

	/**
	 * 登录
	 * User: Clannad ~ ☆
	 * DateTime: 2019/10/31 11:30
	 * @param LoginRequest $request
	 * @throws ResponseException
	 */
	public function login(LoginRequest $request)
    {
		$credentials = $request->only(['username','password']);

		if($token = auth('api')->attempt($credentials)){
		    if(auth('api')->user()->status == 0){
		        throw new ResponseException(403,'账号已经被封禁，禁止登陆');
		    }

			throw new ResponseException(200,'ok',['token'=>$token]);
		}else{
			throw new ResponseException(400,'账号或密码错误');
		}
    }


    /**
     * 微信登录页面
     * User: Clannad ~ ☆
     */
    public function wxLogin()
    {
        $app = app('wechat.official_account');

        $user = $app->oauth->user();

        //获取到了用户的基本信息
        if($user){
            //根据信息去查用户
            $app_user = User::query()->where([
                'wx_openid'=>$user->id
            ])->first();

            //如果有 就颁发token
            if($app_user){

                if($app_user->status == 0){
                    throw new ResponseException(400,'改用户已被锁定');
                }

                $checked = WechatUser::query()->where(['user_id'=>$app_user->id])->first();

                if($checked){
                    //存储access_token
                    WechatUser::query()->where([
                        'user_id'=>$app_user->id,
                    ])->update(['access_token'=>$user->token]);
                }else{
                    //存储access_token
                    WechatUser::query()->create([
                        'user_id'=>$app_user->id,
                        'access_token'=>$user->token
                    ]);
                }

                $token = JWTAuth::fromUser($app_user);
            }else{
                //自动创建用户
                $userData = [
                    'username'    => 'cl_' . time() . mt_rand(1111, 9999),
                    'nick_name'   => $user->nickname,
                    'password'    => bcrypt(123456),
                    'wx_username' => $user->nickname,
                    'thumb'       => $user->avatar,
                    'wx_openid'   => $user->id,
                ];

                $app_user = User::create($userData);
                $app_user->user_info()->create([
                    'age'=>1,
                    'sex'=>0
                ]);

                //存储access_token
                WechatUser::query()->create([
                    'user_id'=>$app_user->id,
                    'access_token'=>$user->token
                ]);

                $token = JWTAuth::fromUser($app_user);
            }

            throw new ResponseException(200,'ok',['token'=>$token]);
        }else{
            throw new ResponseException(400,'授权异常，请联想管理员');
        }
    }

    /**
     * 邀请注册
     * User: Clannad ~ ☆
     * DataTime：2020/8/9 0009 09:28
     * @param Request $request
     * @throws ResponseException
     */
    public function inviteRegister(Request $request)
    {
        $sale_id = $request->input('sale_id');

        $saleman = User::query()->where(['id'=>$sale_id,'status'=>1])->first();

        if(!$saleman){
            throw new ResponseException(404,'邀请人不存在或状态异常');
        }

        //自动创建用户
        $userData = [
            'username'    => 'cl_' . time() . mt_rand(1111, 9999),
            'nick_name'   => '邀请测试用户'.mt_rand(1111,9999),
            'password'    => bcrypt(123456),
            'pid_one'     => $sale_id
        ];

        if($saleman->is_sale_man != 1){
            throw new ResponseException(400,'非营销人员不可邀请注册');
//        }else if($saleman->proxy_level == '0'){
//            $userData['proxy_level'] = 1;
        }else if($saleman->proxy_level == 1){
            $userData['is_sale_man'] = 1;
            $userData['proxy_level'] = 2;
        }else if($saleman->proxy_level == 2){
            $userData['is_sale_man'] = 1;
            $userData['proxy_level'] = 3;
        }
//        else{
//            throw new ResponseException(400,'三级代理商不可再扩展下级人员');
//        }

        //对应业务关系 上上级 (邀请人的上级)
        $parent_two_id = User::query()->where([
            'id'=>$sale_id,
            'status'=>1,
        ])->value('pid_one');

        if($parent_two_id){
            $userData['pid_two'] = $parent_two_id;

            //查第三级 也就是顶级
            $parent_three_id = User::query()->where([
                'id'=>$parent_two_id,
                'status'=>1,
            ])->value('pid_one');

            if($parent_three_id){
                $userData['pid_three'] = $parent_three_id;
            }
        }

        $app_user = User::create($userData);
        $app_user->user_info()->create([
            'age'=>1,
            'sex'=>0
        ]);

        $token = JWTAuth::fromUser($app_user);

        throw new ResponseException(200,'注册成功',$token);
    }

	/**
	 * 退出
	 * User: ihome
	 * @throws ResponseException
	 */
	public function logout()
    {
		JWTAuth::parseToken()->invalidate();
		throw new ResponseException(204,'退出成功');
    }
}
